﻿using ETWJ.DTO;
using ETWJ.Iservice;
using ETWJ.Model;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ETWJ.Service
{
    public class EmployeeService : CommonService<Employee, EmployeeDTO, MyDbContext>, IEmployeeService<Employee,EmployeeDTO>
    {
        
        public async Task<List<EmployeeDTO>> GetAll()
        {
            using (MyDbContext ctx = new MyDbContext())
            {
                List<EmployeeDTO> list = new List<EmployeeDTO>();
                BaseService<Employee> bs = new BaseService<Employee>(ctx);
                await bs.GetAll().AsNoTracking().ForEachAsync(e =>
                {
                    list.Add(AutoMapper.Mapper.Map<EmployeeDTO>(e));
                });
                return list;
            }
        }

        public async Task<int> Update(EmployeeDTO dto)
        {
            using (MyDbContext ctx = new MyDbContext())
            {
                BaseService<Employee> bs = new BaseService<Employee>(ctx);

                var data =await bs.GetByIdAsync(dto.Id);
                
                data.PhoneNum = dto.PhoneNum;
                data.Emaill = dto.Emaill;
                data.EmpId = dto.EmpId;
                data.EmpStatus = dto.EmpStatus;
                data.Leave = dto.Leave;
                data.Name = dto.Name;
                data.Sales = dto.Sales;
                data.UserName = dto.UserName;
                data.UserPwd = dto.UserPwd;
                data.WeChat = dto.WeChat;
                
               
                return await ctx.SaveChangesAsync();
            }
        }

        public async Task<Employee> GetByPhoneNum(string phoneNum)
        {
            using (MyDbContext ctx = new MyDbContext())
            {
                return await ctx.Set<Employee>().Where(e => e.IsDeleted == 0 && e.PhoneNum == phoneNum).FirstOrDefaultAsync();
            }
        }

       
    }
}
